package com.aiti.lulian.service.impl;

import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.EnterpriseDictDataDto;
import com.aiti.lulian.entity.EnterpriseDictData;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.entity.SysData;
import com.aiti.lulian.mapper.EnterpriseDictDataMapper;
import com.aiti.lulian.service.IEnterpriseDictDataService;
import com.aiti.lulian.service.ILuLianEnterpriseService;
import com.aiti.lulian.service.ISysDataService;
import com.aiti.lulian.vo.EnterpriseDictDataVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EnterpriseDictDataServiceImpl extends BaseSerivceImpl<EnterpriseDictDataMapper, EnterpriseDictData> implements IEnterpriseDictDataService {

    @Autowired
    private ISysDataService sysDataService;

    @Autowired
    private ILuLianEnterpriseService luLianEnterpriseService;

    @Override
    public Message addEnterpriseDictData(EnterpriseDictDataDto dto) {
        if (StrUtil.isBlank(dto.getBaseName())) {
            return Message.fail("不能为空");
        }
        EnterpriseDictData enterpriseDictData = new EnterpriseDictData();
        BeanUtils.copyProperties(dto, enterpriseDictData);
        enterpriseDictData.setCreator(dto.getUserId());
        enterpriseDictData.setBaseCreateTime(new Date());
        List<EnterpriseDictData> dictDataList = this.list(new LambdaQueryWrapper<EnterpriseDictData>().eq(EnterpriseDictData::getEnterpriseId, dto.getEnterpriseId())
                .eq(EnterpriseDictData::getDictTypeNo, dto.getDictTypeNo()).orderByDesc(EnterpriseDictData::getSort));
        if (dictDataList.size() == 0) {
            enterpriseDictData.setSort(0);
        } else {
            enterpriseDictData.setSort(dictDataList.get(0).getSort() + 1);
        }
        this.save(enterpriseDictData);
        return Message.success();
    }

    @Override
    public Message updateEnterpriseDictData(EnterpriseDictDataDto dto) {
        if (StrUtil.isBlank(dto.getBaseName())) {
            return Message.fail("不能为空");
        }
        String baseId = dto.getBaseId();
        EnterpriseDictData enterpriseDictData = this.getById(baseId);
        if (StrUtil.equals(enterpriseDictData.getIsUpdated(), "0")) {
            return Message.fail("不可修改");
        }
        EnterpriseDictData dataModel = new EnterpriseDictData();
        BeanUtils.copyProperties(dto, dataModel);
        dataModel.setUpdateBy(dto.getUserId());
        dataModel.setBaseUpdateTime(new Date());
        this.updateById(dataModel);
        return Message.success();
    }

    @Override
    public Message deleteEnterpriseDictData(String baseId, Integer sort, String enterpriseId, String dictTypeNo) {
        this.removeById(baseId);
        //对该顺序以下的数据进行重新排序
        List<EnterpriseDictData> dictDataList = this.list(new LambdaQueryWrapper<EnterpriseDictData>().eq(EnterpriseDictData::getEnterpriseId, enterpriseId)
                .eq(EnterpriseDictData::getDictTypeNo, dictTypeNo).gt(EnterpriseDictData::getSort, sort));
        List<EnterpriseDictData> updatedDictDataList = dictDataList.stream().peek(i -> i.setSort(i.getSort() - 1)).collect(Collectors.toList());
        this.updateBatchById(updatedDictDataList);
        return Message.success();
    }

    @Override
    public List<EnterpriseDictDataVo> getEnterpriseDictList(String enterpriseId, String module, Page<EnterpriseDictData> page) {
        List<EnterpriseDictDataVo> enterpriseDictList = this.baseMapper.selectEnterpriseDictList(enterpriseId, module, page);
        List<EnterpriseDictDataVo> resultList = enterpriseDictList.stream().peek(i -> {
            List<String> moduleIds = Arrays.asList(i.getModule().split(","));
            List<String> moduleNames = sysDataService.getBaseNames(moduleIds);
            i.setModuleName(StrUtil.join(",", moduleNames));
            List<String> dictAllDataName = this.baseMapper.selectDictAllData(i.getDictTypeNo(), enterpriseId);
            i.setDictAllData(dictAllDataName.stream().collect(Collectors.joining(",")));
        }).collect(Collectors.toList());
        return resultList;
    }

    @Override
    public Message getEnterpriseDictDataList(String dictTypeNo, String enterpriseId) {
        List<EnterpriseDictData> enterpriseDictDataList = this.list(new LambdaQueryWrapper<EnterpriseDictData>().eq(EnterpriseDictData::getDictTypeNo, dictTypeNo)
                .eq(EnterpriseDictData::getEnterpriseId, enterpriseId).orderByAsc(EnterpriseDictData::getSort));
        return Message.success(enterpriseDictDataList);
    }

    @Override
    public Message maintainEnterpriseDictData() {
//        List<String> enterpriseIds = luLianEnterpriseService.list(new LambdaQueryWrapper<LuLianEnterprise>().eq(LuLianEnterprise::getIsDelete, "0").eq(LuLianEnterprise::getMiniProgramVersion, 2))
//                .stream().map(LuLianEnterprise::getBaseId).collect(Collectors.toList());
        List<String> enterpriseIds = luLianEnterpriseService.list(new LambdaQueryWrapper<LuLianEnterprise>().eq(LuLianEnterprise::getIsDelete, "0"))
                .stream().map(LuLianEnterprise::getBaseId).collect(Collectors.toList());
        List<SysData> cardCustomerTypeList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_TYPE")
                .orderByAsc(SysData::getBaseId));
        List<SysData> cardCustomerSourceList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_SOURCE")
                .orderByAsc(SysData::getBaseId));
        List<SysData> cardCustomerFollowStatusList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CARD_CUSTOMER_FOLLOW_STATUS")
                .orderByAsc(SysData::getBaseId));
        for (String enterpriseId : enterpriseIds) {
            int i = 0;
            int j = 0;
            int k = 0;
            List<EnterpriseDictData> dataList = new ArrayList<>();
            //默认的客户类型
            for (SysData cardCustomerType : cardCustomerTypeList) {
                EnterpriseDictData cardCustomerTypeDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerType.getDictTypeNo()).dictTypeName("客户类型").baseName(cardCustomerType.getBaseName()).typeId(cardCustomerType.getTypeId())
                        .sort(i ++).isUpdated(StrUtil.equals(cardCustomerType.getBaseId(), "7ee01fe48a2647eb8b549acd28c45899") ? "0" : "1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01")
                        .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                dataList.add(cardCustomerTypeDictData);
            }
            //默认的客户来源
            for (SysData cardCustomerSource : cardCustomerSourceList) {
                EnterpriseDictData cardCustomerSourceDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerSource.getDictTypeNo()).dictTypeName("客户来源").baseName(cardCustomerSource.getBaseName()).typeId(cardCustomerSource.getTypeId())
                        .sort(j ++).isUpdated("1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01")
                        .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                dataList.add(cardCustomerSourceDictData);
            }
            //默认的跟进状态
            for (SysData cardCustomerFollowStatus : cardCustomerFollowStatusList) {
                EnterpriseDictData cardCustomerFollowStatusDictData = EnterpriseDictData.builder().dictTypeNo(cardCustomerFollowStatus.getDictTypeNo()).dictTypeName("跟进状态").baseName(cardCustomerFollowStatus.getBaseName()).typeId(cardCustomerFollowStatus.getTypeId())
                        .sort(k ++).isUpdated((StrUtil.equals(cardCustomerFollowStatus.getBaseId(), "c661b397f83a4fd590f3c79ac4040dad1") || StrUtil.equals(cardCustomerFollowStatus.getBaseId(), "c661b397f83a4fd590f3c79ac4040dad4")) ? "0" : "1").module("8725839a-1488-4c30-9ef4-6d7369e28f00,8725839a-1488-4c30-9ef4-6d7369e28f01,8725839a-1488-4c30-9ef4-6d7369e28f03,8725839a-1488-4c30-9ef4-6d7369e28f04")
                        .enterpriseId(enterpriseId).creator("1").baseCreateTime(new Date()).build();
                dataList.add(cardCustomerFollowStatusDictData);
            }
            this.saveBatch(dataList);
        }
        return Message.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public synchronized Message setEnterpriseDictDataSort(EnterpriseDictDataDto dto) {
        this.updateBatchById(dto.getDictDataList());
        return Message.success();
    }
}
